﻿/*
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.IO;
using Scaffold.Views;
namespace Scaffold
{
    public class ScaffoldWebFormViewEngine : WebFormViewEngine
    {
        public IDictionary<string, ViewPageInfo> ScaffoldViews { get; set; }
        public ScaffoldWebFormViewEngine(IDictionary<string, ViewPageInfo> scaffoldViews)
        {
            this.ViewLocator = new ScaffoldViewLocator();
            ScaffoldViews = scaffoldViews;
        }
        protected override void RenderView(ViewContext viewContext)
        {
            string viewLocation = this.ViewLocator.GetViewLocation(viewContext, viewContext.ViewName);
            string physicalLocation = viewContext.HttpContext.Request.MapPath(viewLocation);

            if (File.Exists(physicalLocation))
            {
                base.RenderView(viewContext);
            }

            else if (ScaffoldViews.ContainsKey(viewContext.ViewName))
            {
                var viewInfo = ScaffoldViews[viewContext.ViewName];
                
                ConstructorInfo ci = viewInfo.Type.GetConstructor(new Type[]{typeof(Scaffold.Views.ViewPageInfo)});
                ViewPage page = (ViewPage) ci.Invoke(new object[]{viewInfo});

                if (!string.IsNullOrEmpty(viewContext.MasterName))
                {
                    string masterLocation = this.ViewLocator.GetMasterLocation(viewContext, viewContext.MasterName);
                    if (string.IsNullOrEmpty(masterLocation))
                    {
                        throw new InvalidOperationException(String.Format("Could not find master page {0}", viewContext.MasterName));
                        //Sthrow new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.WebFormViewEngine_MasterNotFound, new object[] { viewContext.MasterName }));
                    }
                    page.MasterLocation = masterLocation;
                }
                //page.SetViewData(viewContext.ViewData);
                typeof(ViewPage).GetMethod("SetViewData", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(page, new object[] { viewContext.ViewData });

                page.RenderView(viewContext);
            }
            else
            {
                throw new InvalidOperationException("No Such View");
            }
        }
    }
}
